#encoding: utf-8
'''
Created on 2012-4-25

@author: huangjacky
@copyright: TeamV - Group: WhutOJ
目前版本还是采用单独线程的方式，接下来的版本中完善线程池后采用线程池。
'''

from threading import  Thread
import Queue

class PyOJWorker(Thread):
    '''
    工作线程类
    '''
    workCount = 0;
    def __init__(self, oQueue, itimeout):
        Thread.__init__(self)
        self.setDaemon(True)
        self.__id = PyOJWorker.workCount
        PyOJWorker.workCount += 1
        self.__working = False # 工作线程是否正在执行任务
        self.__terminated = False # 是否结束
        self.__queue = oQueue
        self.__timeout = itimeout
    
    @property
    def timeout(self):
        return self.__timeout
    
    @timeout.setter
    def setTimeout(self, value):
        self.__timeout = value
    
    @property
    def queue(self):
        return self.__queue
    
    @property
    def terminated(self):
        return self.__terminated
    
    @terminated.setter
    def setTerminated(self, value):
        self.__terminated = value
        
    def run(self):
        while not self.__terminated:
            # 从队列中取得任务然后运行任务，然后继续等待
            try:
                self.__working = True # 进入工作状态
                # (工作函数，参数，回调函数)
                (func, args, callback) = self.__queue.get(self.__timeout)
                res = func(args)
                callback(res)
            except Queue.Empty:
                pass # 队列空继续等待，除非有指定说要结束了。
            except:
                pass
            finally:
                self.__working = False # 工作结束退出工作状态
        
class PyOJThreadPool(object):
    '''
    线程池类
    '''

    def __init__(self, iCount=10):
        object.__init__(self)
        self.__workQueue = Queue() # 工作队列
        self.__workCount = iCount # x线程池的容量
        self.__workers = [] # 工作线程的集合
        
    
        
        
